package org.osami.phidget.disco;

import java.util.Properties;

import org.apache.felix.ipojo.ComponentInstance;
import org.apache.felix.ipojo.ConfigurationException;
import org.apache.felix.ipojo.Factory;
import org.apache.felix.ipojo.MissingHandlerException;
import org.apache.felix.ipojo.UnacceptableConfiguration;
import org.apache.felix.ipojo.annotations.Component;
import org.apache.felix.ipojo.annotations.Invalidate;
import org.apache.felix.ipojo.annotations.Requires;
import org.apache.felix.ipojo.annotations.Validate;

import com.phidgets.InterfaceKitPhidget;
import com.phidgets.PhidgetException;
import com.phidgets.event.AttachEvent;
import com.phidgets.event.AttachListener;
import com.phidgets.event.DetachEvent;
import com.phidgets.event.DetachListener;

@Component(immediate = true,name="PhidgetDisco")
public class Discovery {
	InterfaceKitPhidget m_phidget;
	private ComponentInstance m_createComponentInstance;

	@Requires(filter = "(factory.name=PhidgetProxyFactory)")
	Factory m_proxyFactory;

	@Validate
	public void init() {
		try {
			
			m_phidget = new InterfaceKitPhidget();
			m_phidget.addAttachListener(new AttachListener() {
				
					public void attached(AttachEvent arg0) {
						System.out.println("[Disco]AttachEvent received.");
					// get params
					try {
						int l_id = arg0.getSource().getSerialNumber();
						Properties l_proProperties = new Properties();
						l_proProperties.put("id", ""+l_id);
						l_proProperties.put("instance", m_phidget);
						
						// Call factory for instance creation
						m_createComponentInstance = m_proxyFactory.createComponentInstance(l_proProperties);
						System.out.println("[Disco]Instance created.");
						
					} catch (PhidgetException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (UnacceptableConfiguration e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (MissingHandlerException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (ConfigurationException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					} catch (Throwable t){
						t.printStackTrace();
					}
				}				
			});
			
			
			
			m_phidget.addDetachListener(new DetachListener() {
				
				public void detached(DetachEvent arg0) {
					if(m_createComponentInstance!= null){
						m_createComponentInstance.dispose();
					}
					
				}
			});
			
			m_phidget.openAny();
			System.out.println("waiting for attachment...");
			
		} catch (PhidgetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	@Invalidate
	public void stop() {

	}

}
